#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
新成员欢迎控制器（合并版本）
将路由和控制器合并到一个类中
"""

from typing import Dict, Any, List, Optional
from flask import Blueprint, request, jsonify
from services.welcome_service import WelcomeService
from utils.R import ApiResponse, R
from settings import get_logger

# API版本
API_VERSION = 'v1'

# 创建蓝图
welcome_bp = Blueprint('welcome', __name__, url_prefix='/api/welcome')

class WelcomeController:
    """
    新成员欢迎控制器
    负责处理新成员欢迎相关的HTTP请求和响应
    """
    
    def __init__(self):
        """
        初始化控制器并注册路由
        """
        self.welcome_service = WelcomeService()
        self.logger = get_logger(__name__)
        self._register_routes()
    
    def _register_routes(self):
        """
        注册路由
        """
        welcome_bp.route('/monitoring/start', methods=['POST'])(self.start_welcome_monitoring)
        welcome_bp.route('/monitoring/stop', methods=['POST'])(self.stop_welcome_monitoring)
        welcome_bp.route('/monitoring/status', methods=['GET'])(self.get_welcome_monitoring_status)
        welcome_bp.route('/template', methods=['POST'])(self.set_welcome_message_template)
        welcome_bp.route('/template', methods=['GET'])(self.get_welcome_message_template)
        welcome_bp.route('/groups', methods=['GET'])(self.get_monitored_groups)
    
    def start_welcome_monitoring(self):
        """
        启动新成员欢迎监听
        
        POST /api/welcome/monitoring/start
        
        Request Body:
        {
            "groups": ["群组1", "群组2"],  // 可选，要监听的群组列表，不传则监听所有群组
            "duration": "24h"              // 可选，监听持续时间，默认24小时
        }
        
        Returns:
            JSON响应
        """
        try:
            # 获取请求参数
            data = request.get_json() or {}
            groups = data.get('groups')  # 可选的群组列表
            duration = data.get('duration', '24h')  # 默认24小时
            
            # 参数验证
            if groups is not None and not isinstance(groups, list):
                response = R.validation_error(message='群组列表参数格式错误，应为数组')
                return response.to_dict(), response.code
            
            if not isinstance(duration, str) or not duration.strip():
                response = R.validation_error(message='持续时间参数格式错误')
                return response.to_dict(), response.code
            
            # 调用服务层业务逻辑
            result = self.welcome_service.start_welcome_monitoring_business_logic(
                groups=groups,
                duration=duration.strip()
            )
            
            # 处理结果
            if result.get('success'):
                return R.ok(
                    data=result.get('data'),
                    message=result.get('message', '新成员欢迎监听已启动')
                )
            else:
                return R.fail(message=result.get('error', '启动新成员欢迎监听失败'))
                
        except Exception as e:
            self.logger.error(f"启动新成员欢迎监听失败: {e}")
            return R.fail(message="启动新成员欢迎监听失败")
    
    def stop_welcome_monitoring(self):
        """
        停止新成员欢迎监听
        
        POST /api/welcome/monitoring/stop
        
        Returns:
            JSON响应
        """
        try:
            # 调用服务层业务逻辑
            result = self.welcome_service.stop_welcome_monitoring_business_logic()
            
            # 处理结果
            if result.get('success'):
                return R.ok(message=result.get('message', '新成员欢迎监听已停止'))
            else:
                return R.fail(message=result.get('error', '停止新成员欢迎监听失败'))
                
        except Exception as e:
            self.logger.error(f"停止新成员欢迎监听失败: {e}")
            return R.fail(message="停止新成员欢迎监听失败")
    
    def get_welcome_monitoring_status(self):
        """
        获取新成员欢迎监听状态
        
        GET /api/welcome/monitoring/status
        
        Returns:
            JSON响应，包含监听状态信息
        """
        try:
            # 调用服务层业务逻辑
            result = self.welcome_service.get_welcome_monitoring_status_business_logic()
            
            # 处理结果
            if result.get('success'):
                return R.ok(
                    data=result.get('data'),
                    message=result.get('message', '获取新成员欢迎监听状态成功')
                )
            else:
                return R.fail(message=result.get('error', '获取新成员欢迎监听状态失败'))
                
        except Exception as e:
            self.logger.error(f"获取新成员欢迎监听状态失败: {e}")
            return R.fail(message="获取新成员欢迎监听状态失败")
    
    def set_welcome_message_template(self):
        """
        设置欢迎消息模板
        
        POST /api/welcome/template
        
        Request Body:
        {
            "template": "欢迎 @{member_name} 加入群聊！🎉"  // 欢迎消息模板，支持 {member_name} 占位符
        }
        
        Returns:
            JSON响应
        """
        try:
            # 获取请求参数
            data = request.get_json() or {}
            template = data.get('template')
            
            # 参数验证
            if not template or not isinstance(template, str):
                response = R.validation_error(message='模板参数格式错误或为空')
                return response.to_dict(), response.code
            
            # 调用服务层业务逻辑
            result = self.welcome_service.set_welcome_message_template_business_logic(template)
            
            # 处理结果
            if result.get('success'):
                return R.ok(
                    data=result.get('data'),
                    message=result.get('message', '欢迎消息模板设置成功')
                )
            else:
                return R.fail(message=result.get('error', '设置欢迎消息模板失败'))
                
        except Exception as e:
            self.logger.error(f"设置欢迎消息模板失败: {e}")
            return R.fail(message="设置欢迎消息模板失败")
    
    def get_welcome_message_template(self):
        """
        获取当前欢迎消息模板
        
        GET /api/welcome/template
        
        Returns:
            JSON响应，包含当前模板
        """
        try:
            # 调用服务层业务逻辑
            result = self.welcome_service.get_welcome_message_template_business_logic()
            
            # 处理结果
            if result.get('success'):
                return R.ok(
                    data=result.get('data'),
                    message=result.get('message', '获取欢迎消息模板成功')
                )
            else:
                return R.fail(message=result.get('error', '获取欢迎消息模板失败'))
                
        except Exception as e:
            self.logger.error(f"获取欢迎消息模板失败: {e}")
            return R.fail(message="获取欢迎消息模板失败")
    
    def get_monitored_groups(self):
        """
        获取可监听的群组列表
        
        GET /api/welcome/groups
        
        Returns:
            JSON响应，包含所有群组和当前监听的群组
        """
        try:
            # 调用服务层业务逻辑
            result = self.welcome_service.get_monitored_groups_business_logic()
            
            # 处理结果
            if result.get('success'):
                return R.ok(
                    data=result.get('data'),
                    message=result.get('message', '获取可监听群组列表成功')
                )
            else:
                return R.fail(message=result.get('error', '获取可监听群组列表失败'))
                
        except Exception as e:
            self.logger.error(f"获取可监听群组列表失败: {e}")
            return R.fail(message="获取可监听群组列表失败")

# 实例化控制器，确保路由被注册
welcome_controller = WelcomeController()